﻿using DavidJalbert.TinyCarControllerAdvance;
using LogSystem;
using NodeCanvas.Framework;
using Pathfinding;
using UnityEngine;
using Yoozoo.Gameplay.Liberty.Media;
using Yoozoo.Gameplay.Liberty.VehicleController;
using Yoozoo.Mars.Got;

namespace Yoozoo.Gameplay.Liberty.AI
{
    public class CarEntity : MonoBehaviour
    {
        public int id;

        public CarData data;

        public VehicleAI vehicleAI;

        public VehicleSetting vehicleSetting;

        public TCCAPlayer carController;

        public VehicleAudioComponent audioComponent;

        public VehicleLodComponent vehicleLodComponent;
        
        public NavmeshCut navmeshCut;

        [SerializeField] private VehicleInteriorComponent _interiorComponent;

        public VehicleInteriorComponent InteriorComponent
        {
            get
            {
                if (_interiorComponent == null)
                {
                    _interiorComponent = GetComponent<VehicleInteriorComponent>();
                }

                return _interiorComponent;
            }
            set => _interiorComponent = value;
        }

        [SerializeField] private GraphOwner _graphOwner;

        public GraphOwner GraphOwner
        {
            get
            {
                if (_graphOwner == null)
                {
                    _graphOwner = GetComponent<GraphOwner>();
                }

                return _graphOwner;
            }
        }
        
        public Transform carBase;

        public AIEntity npcLeft; // 驾驶Npc
        public AIEntity npcRight; // 副驾Npc

        public Vector3 position => carController.GetCarPosition();
                
        public Vector3 forward => carController.GetCarForward();

        public Vector3 right => carController.GetCarRight();
               
        public Collider collider => carController.getCarCollider();

        private void Awake()
        {
            if (audioComponent == null)
            {
                audioComponent = GetComponent<VehicleAudioComponent>();
            }

            if (navmeshCut == null)
            {
                navmeshCut = GetComponent<NavmeshCut>();
            }
        }

        private void OnEnable()
        {
            
        }

        public void SetDestination(Vector3 destination, bool terminal)
        {
            destination.y = 0;
            data.destination = destination;
            data.terminal = terminal;
            vehicleAI.SetDestination(destination, terminal);
        }

        public void SetAIParameters()
        {
            carController.setMotorMaxSpeed(vehicleSetting.aiMaxSpeed);
            transform.gameObject.SetLayerRecursively(LayerMask.NameToLayer("Agent"));
            carController.UpdateCarColliderLayer();
        }

        public void SetPlayerParameters()
        {
            carController.setMotorMaxSpeed(vehicleSetting.playerMaxSpeed);
            transform.gameObject.SetLayerRecursively(LayerMask.NameToLayer("Player"));
            carController.UpdateCarColliderLayer();
        }

        public void EnableVehicle()
        {
            transform.gameObject.SetActive(true);
            if (vehicleSetting.leftSeatPoint && npcLeft)
            {
                vehicleSetting.leftSeatPoint.gameObject.SetActive(true);
                npcLeft.viewer.animationAgent.SetDisableOperate(true);
                npcLeft.viewer.animator.CrossFade("VehicleStateMachine.Car_Drive_Idle", 0, 0);
            }

            carController.setPosition(position);
            carController.setRotation(Quaternion.LookRotation(forward));
            carController.reset();
            carController.immobilize();

            GraphOwner.StartBehaviour();
        }

        public void EnablePassenger()
        {
            if (vehicleSetting.leftSeatPoint && data.driveNpcId != 0)
            {
                AIBirthData npcBirthData = new AIBirthData();
                npcBirthData.uniqueId = NpcUniqueIdUtils.GetVehicleNpcUniqueID(data.uniqueId);
                npcBirthData.isFare = true;
                npcBirthData.position = vehicleSetting.leftSeatPoint.position;
                npcBirthData.forward = vehicleSetting.leftSeatPoint.forward;
                npcBirthData.modelResId = -1;
                npcBirthData.randomModel = true;
                npcBirthData.isStatic = false;
                
                bool success = LibertyAIUtils.AIManager.DynamicNpcManager.AddDynamicNpc(npcBirthData, 1002);
                
                if (success)
                {
                    AIEntity entity = LibertyAIUtils.AIManager.NpcBirthManager.GetNpc(npcBirthData.uniqueId);
                    entity.gameObject.SetActive(false);
                    entity.data.npcStatus = NpcStatus.InCar;
                    entity.viewer.locomotionAgent.enabled = false;
                    entity.characterController.enabled = false;
                    entity.seeker.transform.gameObject.SetActive(false);
                    entity.onHitCollider.gameObject.SetActive(false);
                    entity.headCollider.gameObject.SetActive(false);
                    
                    var entityViewer = entity.viewer.transform.parent;
                    entity.viewer.transform.localScale = new Vector3(0.01f, 0.01f, 0.01f);  // 保证Animator生效
                    entityViewer.parent = vehicleSetting.leftSeatPoint;
                    entityViewer.localPosition = Vector3.zero;
                    entityViewer.localEulerAngles = Vector3.zero;
                    npcLeft = entity;
                    
                    Timers.inst.Add(Time.fixedDeltaTime * 2,1,(o =>
                    {
                        // 切到Idle状态
                        entity.gameObject.SetActive(true);
                        npcLeft.viewer.animationAgent.SetDisableOperate(true);
                        entity.viewer.animator.PlayInFixedTime("VehicleStateMachine.Car_Drive_Idle", 0, 0);
                    }));

                    Timers.inst.Add(Time.fixedDeltaTime * 4, 1, (o =>
                    {
                        // 显示Npc
                        entity.viewer.transform.localScale = Vector3.one;
                    }));

                }
                else
                {
                    Debug.LogError(LogModule.LibertyScene,$"添加车辆Npc失败，车辆ID：{data.uniqueId}");
                }
            }
        }
        
        public void DisableVehicle()
        {
            // if (vehicleSetting.leftSeatPoint)
            // {
            //     vehicleSetting.leftSeatPoint.gameObject.SetActive(false);
            // }
            // if (vehicleSetting.rightSeatPoint)
            // {
            //     vehicleSetting.rightSeatPoint.gameObject.SetActive(false);
            // }
            transform.gameObject.SetActive(false);
            // carController.immobilize();
            // carController.reset();
        }

        public void DisablePassenger()
        {
            if (vehicleSetting.leftSeatPoint && npcLeft)
            {
                vehicleSetting.leftSeatPoint.gameObject.SetActive(false);
            }
        }
    }
}